package com.store.app.fragment;

import android.graphics.Bitmap;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.zxing.Result;
import com.store.app.activity.CashierActivity;
import com.store.app.bean.GoodsListBean;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.scan.CameraManager;
import com.store.app.utils.scan.CameraPreview;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/3/1.
 */
public class ScanFragment extends Capture_ZxingFragment implements IOnHttpListener{
    private View v;
    private FrameLayout scanPreview;               //显示扫描视图
    private ImageView scanLine;                    //二维码视图横线
    private ImageScanner mImageScanner;
    private CameraManager mCameraManager;
    private Camera mCamera;
    private RelativeLayout scanContainer;
    private RelativeLayout scanCropView;
    private Handler autoFocusHandler;
    private boolean previewing = true;
    private Rect mCropRect = null;
    private boolean barcodeScanned = false;
    private List<String> listScan = new ArrayList<>();//扫描过后的产品
    private String tempResult;
    private final int SUCC=1;
    private final int FAIL=2;
    private GoToLogin goToLogin;
    private NetRequest netRequest;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FAIL:
                    Toast.makeText(getActivity(), "商品未录入", Toast.LENGTH_SHORT).show();
                    Timer timer1 = new Timer();
                    TimerTask task1 = new TimerTask(){
                        public void run(){
                            if(mCamera!=null){
                                barcodeScanned = false;
                            }
                            cancel();
                        }
                    };
                    timer1.schedule(task1, 2500);
                    break;
                case SUCC:
                     Timer timer = new Timer();
                    TimerTask task = new TimerTask(){
                        public void run(){
                            if(mCamera!=null){
                                barcodeScanned = false;
                            }
                            cancel();
                        }
                    };
                    timer.schedule(task, 2500);
                    break;
            }
        }
    };


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        netRequest = new NetRequest(this,getActivity());
        Log.v("zyl", "onCreate:ScanFragment");
    }


    private static final long VIBRATE_DURATION = 200L;
    Camera.PreviewCallback previewCb = new Camera.PreviewCallback() {//未使用
        public void onPreviewFrame(byte[] data, Camera camera) {
            if(barcodeScanned==false){
            Camera.Size size = camera.getParameters().getPreviewSize();

            // 这里需要将获取的data翻转一下，因为相机默认拿的的横屏的数据
            byte[] rotatedData = new byte[data.length];
            for (int y = 0; y < size.height; y++) {
                for (int x = 0; x < size.width; x++)
                    rotatedData[x * size.height + size.height - y - 1] = data[x + y * size.width];
            }

            // 宽高也要调整
            int tmp = size.width;
            size.width = size.height;
            size.height = tmp;
            initCrop();
            Image barcode = new Image(size.width, size.height, "Y800");
            barcode.setData(rotatedData);
            barcode.setCrop(mCropRect.left, mCropRect.top, mCropRect.width(),
                    mCropRect.height());

            int result_int = mImageScanner.scanImage(barcode);
            String result = null;

            if (result_int != 0) {
                SymbolSet syms = mImageScanner.getResults();
                for (Symbol sym : syms) {
                    result = sym.getData();
                }
            }


            Log.v("zyl", "barcodeScanned:" + barcodeScanned);

            if (!TextUtils.isEmpty(result) && barcodeScanned==false) {
                tempResult = result;
                barcodeScanned = true;
                Log.v("zyl", "扫描出来的结果是:" + result);
//                new Get_Info(result).start();
                netRequest.requestGoodsDetailsByBarcode(1,result);
                Vibrator vibrator = (Vibrator) getActivity().getSystemService(getActivity().VIBRATOR_SERVICE);
                vibrator.vibrate(VIBRATE_DURATION);

            }
        }
        }
    };

    @Override
    public void handleDecode(Result result, Bitmap barcode) {
        if (!TextUtils.isEmpty(result.getText()) && barcodeScanned==false) {
            tempResult = result.getText();
            barcodeScanned = true;
            Log.v("zyl", "扫描出来的结果是:" + result);
//            new Get_Info(result.getText()).start();
            netRequest.requestGoodsDetailsByBarcode(1,result.getText());
            Vibrator vibrator = (Vibrator) getActivity().getSystemService(getActivity().VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);

        }

    }

    @Override
    public void onResume() {
        super.onResume();
        previewing=true;
        barcodeScanned = false;
    }
    @Override
    public void onPause() {
        super.onPause();
        releaseCamera();
    }
    // Mimic continuous auto-focusing
    Camera.AutoFocusCallback autoFocusCB = new Camera.AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            autoFocusHandler.postDelayed(doAutoFocus, 1000);
        }
    };
    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            if (previewing)
                mCamera.autoFocus(autoFocusCB);
        }
    };



    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    private void decodeEWM(){

    }

    private void initScan() {//未调用
        if (mCamera != null) {
            mCamera.setPreviewCallbackWithBuffer(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        mImageScanner = new ImageScanner();
        mImageScanner.setConfig(0, Config.X_DENSITY, 3);
        mImageScanner.setConfig(0, Config.Y_DENSITY, 3);
        //获得焦点处理的handler
        autoFocusHandler = new Handler();
        mCameraManager = new CameraManager(getActivity());
        try {
            //打开设备管理
            mCameraManager.openDriver();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(),"照相权限已被关闭!",Toast.LENGTH_SHORT).show();
            return;
        }
        //拿到硬件的相机
        mCamera = mCameraManager.getCamera();
        CameraPreview mPreview = new CameraPreview(getActivity(), mCamera, previewCb, autoFocusCB);
        scanPreview.addView(mPreview);

        TranslateAnimation animation = new TranslateAnimation(4, 0.0f, 4, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT,
                0.85f);
        animation.setDuration(3000);
        animation.setRepeatCount(-1);
        animation.setRepeatMode(Animation.REVERSE);
        scanLine.startAnimation(animation);
    }

    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 初始化截取的矩形区域
     */
    private void initCrop() {//未使用
        int cameraWidth = mCameraManager.getCameraResolution().y;
        int cameraHeight = mCameraManager.getCameraResolution().x;

        /** 获取布局中扫描框的位置信息 */
        int[] location = new int[2];
        scanCropView.getLocationInWindow(location);

        int cropLeft = location[0];
        int cropTop = location[1] - getStatusBarHeight();

        int cropWidth = scanCropView.getWidth();
        int cropHeight = scanCropView.getHeight();

        /** 获取布局容器的宽高 */
        int containerWidth = scanContainer.getWidth();
        int containerHeight = scanContainer.getHeight();

        /** 计算最终截取的矩形的左上角顶点x坐标 */
        int x = cropLeft * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的左上角顶点y坐标 */
        int y = cropTop * cameraHeight / containerHeight;

        /** 计算最终截取的矩形的宽度 */
        int width = cropWidth * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的高度 */
        int height = cropHeight * cameraHeight / containerHeight;

        /** 生成最终的截取的矩形 */
        mCropRect = new Rect(x, y, width + x, height + y);
    }

    @Override
    public void onAfinalFail() {
        reCapture();
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if(requestId == 1){
            try {
                JSONObject jsonObjectData = new JSONObject(result);
                JSONArray jsonArray = jsonObjectData.getJSONArray("list");
                if(jsonArray.length()==0){
                    ToastTools.showShort(getActivity(),"商品不存在");
                    reCapture();
                    return;
                }else if(jsonArray.length()>=1){
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    GoodsListBean goodsListBean = new GoodsListBean();
                    goodsListBean.setCount(1);
                    goodsListBean.setPrice(jsonObject.get("market_price") + "");
                    goodsListBean.setGoodsName(jsonObject.get("goods_name") + "");
                    String mk = jsonObject.getString("market_price");
                    handler.sendEmptyMessage(SUCC);
                    CashierActivity.goodsListBeanList.add(goodsListBean);
                    CashierActivity.handler.sendEmptyMessage(1);
                }

                reCapture();

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if(requestId == 1){
            handler.sendEmptyMessage(FAIL);
            reCapture();
        }
    }



    private void reCapture(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                barcodeScanned=false;
                setReCapture();  //重扫
            }
        },3000);
    }

}
